#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansucolDingXiPolicy(BaseTaxPolicySpider):
    name = 'gansu_dingxi_qu_dataproxy_policy'
    
    province = '甘肃省'
    city: str = "定西市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    page_size: int = 15 * 3

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 240,
                # 'CONCURRENT_REQUESTS': 1,
                "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 412, 407],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            # ['安定区人民政府', "安定区", "http://www.anding.gov.cn/col/col1114/index.html?number=E000016"],
            # ['安定区人民政府', "安定区", "http://www.anding.gov.cn/col/col1115/index.html?number=E000017"],
            ['通渭县人民政府', "通渭县", "http://www.tongwei.gov.cn/col/col7051/index.html?number=TW1301"],
            ['通渭县人民政府', "通渭县", "http://www.tongwei.gov.cn/col/col7052/index.html?number=TW1302"],
            ['通渭县发展和改革局', "通渭县", "http://www.tongwei.gov.cn/col/col13977/index.html"],
            ['通渭县人力资源和社会保障局', "通渭县", "http://www.tongwei.gov.cn/col/col14003/index.html"],
            ['通渭县工业和信息化局', "通渭县", "http://www.tongwei.gov.cn/col/col14046/index.html"],
            ['通渭县文体旅游局', "通渭县", "http://www.tongwei.gov.cn/col/col14126/index.html"],
            ['渭源县人民政府', "渭源县", "http://www.cnwy.gov.cn/col/col970/index.html?number=E0014"],
            ['渭源县人民政府', "渭源县", "http://www.cnwy.gov.cn/col/col972/index.html?number=E0016"],
            # ['临洮县人民政府', "临洮县", "http://www.lintao.gov.cn/col/col6958/index.html?number=LD0102"],
            # ['临洮县人民政府', "临洮县", "http://www.lintao.gov.cn/col/col6960/index.html?number=LD0104"],
        ]:
            yield scrapy.Request(url, callback=self._parser_dataproxy_html, meta={"item": {'source': source, 'county': county}})

    def _parser_dataproxy_html(self, response):
        meta = response.meta
        next_url = response.xpath('.').re_first(r"""\[CDATA\[<a href="(.*?)"></a>\]\]></nextgroup>""")
        url_model = urllib.parse.urlparse(next_url)
        url = response.urljoin(response.url.split('/col/')[0] + url_model.path)
        params = {"startrecord": 1, "endrecord": self.page_size * 3, "perpage": self.page_size, }
        data = dict(urllib.parse.parse_qsl(url_model.query))
        if "webname" in data:
            data["webname"] = urllib.parse.unquote(data["webname"])
        data['col'] = data['sourceContentType'] = '1'
        data.pop('page')
        if response.url:
            headers = {"Referer": response.url}
        else:
            headers = {}
        if url[-1] != "?":
            url += "?"
        temp_url = url
        temp_url += urllib.parse.urlencode(params)
        meta.update({
            "params": params,
            "data": data,
            "url": url,
            "headers": headers,
        })
        yield self.FormRequest(
            temp_url,
            formdata=data,
            method="POST",
            headers=headers,
            callback=self.parse_list,
            meta=meta
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        url = meta['url']
        for elem in response.xpath("//record"):
            item = Item()
            url_select = elem.xpath("./text()").get()
            item['source_url'] = scrapy.Selector(text=url_select).xpath(".//a[contains(@href, 'htm')]/@href").get()
            item['source_url'] = response.urljoin(item['source_url'])
            # item['publish_date'] = elem['publishedTimeStr'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        total_page = int(response.xpath("string(//totalpage)").get())
        totalrecord = int(response.xpath("string(//totalrecord)").get())
        page = meta.get('page', 1)
        total_page = math.ceil(int(total_page) / 3)
        print(meta['data'], page, "total_page", total_page, totalrecord)
        if total_page and page < total_page:
            page += 1
            params = {
                "startrecord": ((page - 1) * self.page_size * 3) + 1,
                "endrecord": page * self.page_size * 3,
                "perpage": self.page_size,
            }
            meta['params'] = params
            meta['page'] = page
            temp_url = url
            temp_url += urllib.parse.urlencode(params)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 params: {params}")
            yield self.FormRequest(
                temp_url,
                formdata=meta['data'],
                method="POST",
                meta=meta,
                headers=meta['headers'],
                callback=self.parse_list
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_dingxi_qu_dataproxy_policy".split())
